<template>
  <div class="audio-record">
    <div v-if="type == 1" class="audio-record-1">
      <el-button
        class="record-btn"
        :class="this.isDisabled ? 'not-click' : 'click'"
        icon="el-icon-microphone"
        circle
        v-show="!isRecord"
        @click="clickStart"
      >
      </el-button>
      <el-button
        class="record-btn"
        :class="this.isDisabled ? 'not-click' : 'click'"
        icon="el-icon-video-pause "
        circle
        v-show="isRecord"
        @click="clickStop"
      >
      </el-button>
    </div>
    <div v-if="type == 2" class="audio-record-2">
      <i
        class="record-btn font_family icon-tianchongxing-"
        :class="this.isDisabled ? 'not-click' : 'click'"
        v-show="!isRecord"
        @click="clickStart"
      ></i>
      <i
        class="record-btn font_family icon-zanting1"
        :class="this.isDisabled ? 'not-click' : 'click'"
        v-show="isRecord"
        @click="clickStop"
      ></i>
    </div>
  </div>
</template>

<script>
export default {
  name: "AudioRecord",
  data() {
    return {
      recorder: null,
      isRecord: false,
      timer: null,
      isLoading: true,
    };
  },
  methods: {
    clickStop() {
      if (this.isDisabled) {
        return;
      }
      this.stopRecorder();
      this.$emit("clickEnd");
    },
    clickStart() {
      if (this.isDisabled) {
        return;
      }
      this.startRecorder();
      this.$emit("clickStart");
    },
    setTimer() {
      this.timer = setTimeout(() => {
        this.clickStop();
        this.clearTimer();
      }, this.maxTime);
    },
    clearTimer() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
    },
    /**
     *  录音的具体操作功能
     * */
    // 开始录音
    startRecorder() {
      this.$emit("beforeSatrt");
      this.recorder.start().then(
        () => {
          this.isRecord = true;
          this.$emit("start");
          this.setTimer();
        },
        (error) => {
          // 出错了
          this.clearTimer();
          this.recorder.stop();
          if (error.name == "NotAllowedError") {
            this.$message({
              type: "error",
              message: `没有使用麦克风的权限`,
            });
          } else if (
            error.name == "NotFoundError" &&
            error.message == "Requested device not found"
          ) {
            this.$message({
              type: "error",
              message: `没有找到麦克风`,
            });
          } else {
            this.$message({
              type: "error",
              message: `${error.name} : ${error.message}`,
            });
          }
          throw new Error(error);
        }
      );
    },
    // 继续录音
    resumeRecorder() {
      this.recorder.resume();
    },
    // 暂停录音
    pauseRecorder() {
      this.recorder.pause();
    },
    // 结束录音
    stopRecorder() {
      this.recorder.stop();
      this.isRecord = false;
      this.$emit("ended");
      this.clearTimer();
    },
    // 录音播放
    playRecorder() {
      this.recorder.play();
    },
    // 暂停录音播放
    pausePlayRecorder() {
      this.recorder.pausePlay();
    },
    // 恢复录音播放
    resumePlayRecorder() {
      this.recorder.resumePlay();
    },
    // 停止录音播放
    stopPlayRecorder() {
      this.recorder.stopPlay();
    },
    // 销毁录音
    destroyRecorder() {
      this.recorder.destroy().then(function () {
        this.recorder = null;
      });
    },
    /**
     *  获取录音文件
     * */
    getRecorder() {
      //   let toltime = recorder.duration; //录音总时长
      //   let fileSize = recorder.fileSize; //录音总大小

      //   //录音结束，获取取录音数据
      //   let PCMBlob = recorder.getPCMBlob(); //获取 PCM 数据
      //   let wav = recorder.getWAVBlob(); //获取 WAV 数据

      //   let channel = recorder.getChannelData(); //获取左声道和右声道音频数据

      // debugger;
    },
    /**
     *  下载录音文件
     * */
    //下载pcm
    downPCM() {
      //这里传参进去的时文件名
      this.recorder.downloadPCM("新文件");
    },
    //下载wav
    downWAV() {
      //这里传参进去的时文件名
      this.recorder.downloadWAV("新文件");
    },
    /**
     *  获取麦克风权限
     * */
    getPermission() {
      this.$Recorder.getPermission().then(
        () => {
          console.log("获取权限成功");
        },
        (error) => {
          console.log(`${error.name} : ${error.message}`);
        }
      );
    },
    /**
     * 文件格式转换 wav-map3
     * 获取MP3
     * */
    getMp3Data() {
      this.isLoading = true;
      const mp3Blob = this.convertToMp3(this.recorder.getWAV());
      this.isLoading = false;
      // this.recorder.download(mp3Blob, "recorder", "mp3");
      return mp3Blob;
    },
    convertToMp3(wavDataView) {

    
      // 获取wav头信息
      const wav = this.$lamejs.WavHeader.readHeader(wavDataView); // 此处其实可以不用去读wav头信息，毕竟有对应的config配置
      
      const { channels, sampleRate } = wav;
      
      const mp3enc = new this.$lamejs.Mp3Encoder(channels, sampleRate, 128);

      // 获取左右通道数据
      const result = this.recorder.getChannelData();
      const buffer = [];

      const leftData =
        result.left &&
        new Int16Array(result.left.buffer, 0, result.left.byteLength / 2);
      const rightData =
        result.right &&
        new Int16Array(result.right.buffer, 0, result.right.byteLength / 2);
      const remaining = leftData.length + (rightData ? rightData.length : 0);
      
      const maxSamples = 1152;
      for (let i = 0; i < remaining; i += maxSamples) {
        const left = leftData.subarray(i, i + maxSamples);
        let right = null;
        let mp3buf = null;

        if (channels === 2) {
          right = rightData.subarray(i, i + maxSamples);
          mp3buf = mp3enc.encodeBuffer(left, right);
        } else {
          mp3buf = mp3enc.encodeBuffer(left);
        }

        if (mp3buf.length > 0) {
          buffer.push(mp3buf);
        }
      }

      const enc = mp3enc.flush();

      if (enc.length > 0) {
        buffer.push(enc);
      }
      return new Blob(buffer, { type: "audio/mp3" });
    },
  },
  created() {
    this.recorder = new this.$Recorder({
      sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
      sampleRate: 48000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
      numChannels: 1, // 声道，支持 1 或 2， 默认是1
      // compiling: false, //(0.x版本中生效,1.x增加中)  是否边录边转换，默认是false
    });
    // 绑定事件-打印的是当前录音数据
    this.recorder.onprogress = function (params) {
      // console.log('--------------START---------------')
      console.log("录音时长(秒)", params.duration);
      // console.log("录音大小(字节)", params.fileSize);
      // console.log('录音音量百分比(%)', params.vol);
      // console.log('当前录音的总数据([DataView, DataView...])', params.data);
      // console.log('--------------END---------------')
    };
  },
  props: {
    type: {
      type: Number,
      default: 1,
    },
    maxTime: {
      type: Number,
      default: 40000,
    },
    isDisabled: {
      type: Boolean,
      default: function () {
        return this.$store.getters.isTeacher;
      },
    },
  },
};
</script>